package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-18
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    IApBehaviorEntryService entryService;

    /**
     * 点赞或取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveLike(LikesBehaviorDto dto) {


        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(dto.getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());

        ApBehaviorEntry entry = entryService.getEntry(entryDto);

        ApLikesBehavior likesBehavior = new ApLikesBehavior();

        likesBehavior.setArticleId(Long.valueOf(dto.getArticleId()));
        likesBehavior.setCreatedTime(new Date());
        likesBehavior.setEntryId(Integer.valueOf(entry.getEntryId()));
        likesBehavior.setOperation(dto.getOperation());
        likesBehavior.setType(dto.getType());

        LambdaQueryWrapper<ApLikesBehavior> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApLikesBehavior::getArticleId,dto.getArticleId());

        ApLikesBehavior one = this.getOne(wrapper);


        if (one==null) {

                this.save(likesBehavior);

        }else {
            if (one.getOperation()!=dto.getOperation()) {
                one.setOperation(dto.getOperation());
                this.updateById(one);
            }
        }

        User user = AppThreadLocalUtil.get();
        System.err.println(user);

        return ResponseResult.okResult();
    }

    @Override
    public ApLikesBehavior getLike() {

        LambdaQueryWrapper<ApLikesBehavior> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ApLikesBehavior::getArticleId,1482027609037512705L);

        ApLikesBehavior byId = this.getById(1482027609037512705L);

        return byId;
    }
}
